import { memo, useEffect, useRef, useState } from "react"
import './index.scss'
import UserCard from "./userCard"
import { message, Tooltip } from "antd"
import classNames from "classnames"
import socketService from "../../services/socketService"
import { useAppSelector } from "../../utils/storeHook/storeHook"
import TextChat from "../TextChat/TextChat"

interface propsT{
    actChannelId:string
}

interface userT{
    avatar_url:string;
    username:string;
    user_id:string;
}

const VoiceChat = memo(({actChannelId}:propsT)=>{
    const isConnect = useAppSelector(state=>state.server.isConnect)
    const curUserId = useAppSelector(state=>state.auth.user_id)
    const [messageApi, contextHolder] = message.useMessage()

    const [voiceChated,setVoiceChated] = useState(false)
    const textChatRef = useRef<HTMLDivElement>(null)

    const localStream = useRef<MediaStream>(null)
    const userCards = useRef<{[userId: string]:HTMLDivElement}>({})
    const audioRefs = useRef<{[userId: string]: HTMLAudioElement}>({});
    const peerConnections = useRef<{[key: string]: RTCPeerConnection}>({}) // 新增：存储所有peer连接
    // 添加音量监测状态
    const [userVolumes, setUserVolumes] = useState<Record<string, number>>({});

    const [chatRoomUsers,setChatRoomUsers] = useState<userT[]>([])

    const soundTimmer = useRef<NodeJS.Timeout>(null)
    const domLoading = useRef<NodeJS.Timeout>(null)

    // // 添加录音状态和引用
    // const [isRecording, setIsRecording] = useState(false);
    // const mediaRecorderRef = useRef<MediaRecorder | null>(null);
    // const recordedChunksRef = useRef<Blob[]>([]);
    // const recordingIntervalRef = useRef<NodeJS.Timeout | null>(null);
    // const audioContextRef = useRef<AudioContext | null>(null);
    // const audioSourcesRef = useRef<MediaStreamAudioSourceNode[]>([]);

    // 添加到 ref 数组
    const addToCardRefs = (el: HTMLDivElement | null, id: string) => {
        if (el && !userCards.current[id]) {
            userCards.current[id] = el;
        }
    };
    const addToRefs = (el: HTMLAudioElement | null, id: string) => {
        if (el && !audioRefs.current[id]) {
            audioRefs.current[id] = el;
        }
    };

    // 获取音频流
    const getLocalStream = async (): Promise<MediaStream>=>{
        if (localStream.current) return localStream.current;
        // 高级音频约束（启用AEC）
        const constraints: MediaStreamConstraints = {
            audio: {
                // 开启回声消除等高级功能
                echoCancellation: { ideal: true },
                noiseSuppression: { ideal: true },
                autoGainControl: { ideal: true },
                // 使用语音优化参数
                sampleRate: 48000,
                channelCount: 1,
                sampleSize: 16,
            },
            video: false,
        };
        const stream = await navigator.mediaDevices.getUserMedia(constraints)

        localStream.current = stream
        
        return stream

    }

    function setupAudioLevelMonitor(stream: MediaStream, userId: string) {
        const audioContext = new AudioContext();
        const analyser = audioContext.createAnalyser();
        const microphone = audioContext.createMediaStreamSource(stream);
        microphone.connect(analyser);
        
        analyser.fftSize = 128;
        const dataArray = new Uint8Array(analyser.frequencyBinCount);
        
        const checkVolume = () => {
            analyser.getByteFrequencyData(dataArray);
            let sum = 0;
            for (let i = 0; i < dataArray.length; i++) {
                sum += dataArray[i];
            }
            const average = sum / dataArray.length;
            
            // 将音量映射到0-100范围
            const volume = Math.min(Math.max(average, 0), 100);
            
            setUserVolumes(prev => ({...prev, [userId]: volume}));
            
            if (document.visibilityState === 'visible') {
                requestAnimationFrame(checkVolume);
            }
        };
        
        checkVolume();
    }

    // 为每个用户创建RTCPeerConnection
    const createPeerConnection = async (userId: string) => {
        console.log(1231313213);
        
        if (peerConnections.current[userId]) {
            return peerConnections.current[userId];
        }
        const pc = new RTCPeerConnection({
            iceServers: [
                // {
                //     urls:[
                //         'stun:stun.l.google.com:19302',
                //         'stun:stun1.l.google.com:19302',
                //         'stun:stun2.l.google.com:19302',
                //         'stun:stun3.l.google.com:19302',
                //         'stun:stun4.l.google.com:19302',
                //         'stun:global.stun.twilio.com:3478',
                //         'stun:stun.voipbuster.com:3478',
                //         'stun:stun.voipstunt.com:3478',
                //         'stun:stun.ekiga.net:3478',
                //         'stun:stun.ideasip.com:3478',
                //         'stun:stun.sipgate.net:3478',
                //         'stun:stun.iptel.org:3478',
                //         'stun:stun.services.mozilla.com:3478',
                //     ]
                // },
                // TURN服务器（中继核心）
                {
                    urls: [
                        "turns:turn.xingkdsite.top:5349",    // 加密中继(首选)
                        "turn:turn.xingkdsite.top:3478?transport=tcp", // TCP降级方案
                        "turn:turn.xingkdsite.top:3478"       // UDP保底
                    ],
                    username: "xingk",
                    credential: "etdxf020410"
                }
            ],
            iceCandidatePoolSize: 10, // 增加候选池大小
            bundlePolicy: 'max-bundle', // 优化打包策略
            rtcpMuxPolicy: 'require' // 要求RTCP复用
        });

        // 添加ICE重连逻辑
        // let iceRestartTimer: NodeJS.Timeout | null = null;
        let iceRestartCount = 0; // 重启计数器
        const maxIceRestart = 10;
        
        // 监听远程媒体流
        pc.ontrack = (event) => {
            // console.log('收到轨道事件:', event);
            // console.log('轨道类型:', event.track.kind);
            // console.log('轨道ID:', event.track.id);
            // console.log('流ID:', event.streams[0].id);
            if (event.streams.length > 0 && event.streams[0].id !== curUserId) {
                const remoteStream = event.streams[0];
                
                const audioElement = audioRefs.current[userId];
                if (audioElement) {
                    
                    if (audioElement.srcObject !== remoteStream) {
                        audioElement.srcObject = remoteStream;
                        setupAudioLevelMonitor(remoteStream,userId)
                        
                        console.log(`为 ${userId} 设置远程流`, remoteStream);
                        audioElement.play().catch(e => 
                            console.error("播放失败:", e)
                        );
                        // 改进的播放处理
                        const playAudio = async () => {
                            try {
                                if (audioElement.paused) {
                                    await audioElement.play();
                                }
                                console.log('播放音频',audioElement);
                                
                            } catch (e) {
                                console.error("播放失败:", e);
                                // 延迟重试
                                setTimeout(() => {
                                    if (!audioElement.paused) return;
                                    playAudio();
                                }, 1000);
                            }
                        };
                        
                        playAudio();
                    }
                }
            }
        };

        // ICE候选交换
        pc.onicecandidate = (event) => {
            if (event.candidate) {
                socketService.sendIceCandidate(actChannelId, event.candidate, userId);
            }
        };

        // 添加连接状态监听
        pc.onconnectionstatechange = () => {
            console.log(`与 ${userId} 的连接状态:`, pc.connectionState);
            if(pc.connectionState === 'connected'){
                userCards.current[userId].style.opacity = '1';
            }
        };
        
        pc.oniceconnectionstatechange = () => {
            // console.log(`与 ${userId} 的ICE连接状态:`, pc.iceConnectionState);
    
            // 处理所有失败情况
            if (['failed', 'disconnected'].includes(pc.iceConnectionState)) {
                // 首次失败时立即重启ICE
                if (iceRestartCount === 0) {
                    iceRestartCount++;
                    console.warn(`首次ICE失败，立即重启 (${
                        iceRestartCount}/${maxIceRestart})`);
                    pc.restartIce();
                    return;
                }
                
                // 指数退避策略
                const delay = Math.min(5000, 1000 * Math.pow(2, iceRestartCount));
                console.warn(`${
                    delay/1000
                    }秒后重启ICE (${
                    iceRestartCount + 1}/${maxIceRestart})`);
                
                setTimeout(() => {
                    if (iceRestartCount < maxIceRestart) {
                        iceRestartCount++;
                        pc.restartIce();
                    } else {
                        console.error(`与 ${userId} 的ICE连接已超过最大重试次数，开始重新连接`);
                        recreatePeerConnection(userId);
                    }
                }, delay);
            }
            
            // 重置计数当连接成功时
            if (pc.iceConnectionState === 'connected') {
                iceRestartCount = 0;
            }
        };

        pc.onnegotiationneeded = () => console.log(`与 ${userId} 需要重新协商`);
        pc.onsignalingstatechange = () => console.log(`与 ${userId} 的信令状态:`, pc.signalingState);
        pc.onicegatheringstatechange = () => console.log(`与 ${userId} 的ICE收集状态:`, pc.iceGatheringState);

        peerConnections.current[userId] = pc;
        return pc;
    };

    // 完整ICE重连功能
    const recreatePeerConnection = async (userId: string) => {
        console.log(`重建与 ${userId} 的PeerConnection`);
    
        // 1. 关闭旧连接
        const oldPc = peerConnections.current[userId];
        if (oldPc) {
            oldPc.close();
            delete peerConnections.current[userId];
        }
    
        // 2. 创建新连接
        const pc = await createPeerConnection(userId);
    
        // 3. 重新发起offer
        try {
            const offer = await pc.createOffer({
            iceRestart: true, // 强制ICE重启
            offerToReceiveAudio: true
            });
            
            await pc.setLocalDescription(offer);
            if(!pc.localDescription) return
            socketService.sendOffer(actChannelId, pc.localDescription, userId);
            
        } catch (error) {
            console.error(`重建PeerConnection失败:`, error);
            // 失败处理...
        }
    };

    // 处理offer
    async function onOffer(data: {channel_id: string, offer: RTCSessionDescriptionInit, from_user_id: string}){
        const { offer, from_user_id } = data;
        const pc = peerConnections.current[from_user_id]
        
        if(!pc || from_user_id === curUserId) return;
        
        try {
            await pc.setRemoteDescription(new RTCSessionDescription(offer));
            const answer = await pc.createAnswer();
            await pc.setLocalDescription(answer);
            socketService.sendAnswer(actChannelId, answer, from_user_id);
            
        } catch (error) {
            console.error("处理offer时出错:", error);
        }
    }

    // 处理answer
    async function onAnswer(data: {channel_id: string, answer: RTCSessionDescriptionInit, from_user_id: string}){
        const { answer, from_user_id } = data;
        const pc = peerConnections.current[from_user_id];
        
        if (!pc) {
            return console.log("无法处理answer，因为与用户不存在的连接");
        }
        // 添加状态检查，避免在stable状态下重复设置
        if (pc.signalingState !== 'stable') {
            try {
                await pc.setRemoteDescription(answer);
            } catch (e) {
                console.error("设置远程answer失败:", e);
            }
        } else {
            console.warn("忽略在stable状态下的answer设置");
        }
        
    }


    // 处理ICE候选
    async function onIceCandidate(data: {channel_id: string, candidate: RTCIceCandidateInit, from_user_id: string}){
        const { candidate, from_user_id } = data;
        const pc = peerConnections.current[from_user_id];
        
        if (pc && candidate) {
             try {
                // 确保候选完整
                if (candidate.candidate && candidate.sdpMid && candidate.sdpMLineIndex !== undefined) {
                    await pc.addIceCandidate(new RTCIceCandidate(candidate));
                    console.log(`成功添加来自${from_user_id}的ICE候选`);
                } else {
                    console.warn("收到无效ICE候选:", candidate);
                }
            } catch (e) {
                console.error("添加ICE候选失败:", e);
            }
        }
    }

    // 用户离开处理
    const handleUserLeft = (user_id: string) => {
        setChatRoomUsers(prev => prev.filter(user => user.user_id !== user_id));
        
        const pc = peerConnections.current[user_id];
        if (pc) {
            pc.close();
            delete peerConnections.current[user_id];
            
            console.log(`关闭与 ${user_id} 的Peer连接`);
        }
    };

    async function toggleConnect(){
        setVoiceChated(!voiceChated)
        if(voiceChated){
            // 清理事件监听
            socketService.offOffer();
            socketService.offAnswer();
            socketService.offIceCandidate();
            socketService.offUserLeft()
            socketService.offUserJoined()
            socketService.leaveVoiceChat(actChannelId)
            setChatRoomUsers(prev=>prev.filter(item=>item.user_id!==curUserId))
            if(localStream.current) {
                localStream.current.getTracks().forEach(track => track.stop())
                localStream.current = null;
            }
            // 关闭所有peer连接
            Object.values(peerConnections.current).forEach(pc => pc.close());
            delete audioRefs.current[curUserId]
            delete userCards.current[curUserId]
            Object.values(userCards.current).forEach(card => card.style.opacity = '0')
            peerConnections.current = {}
        } else {
            
            // 注册socket事件
            socketService.onOffer(onOffer);
            socketService.onAnswer(onAnswer);
            socketService.onIceCandidate(onIceCandidate);
            socketService.onUserLeft(handleUserLeft);
            
            const stream = await getLocalStream();
            localStream.current = stream;
            
            // 监听其他用户加入
            socketService.onUserJoined(({user_id}) => {
                if (user_id === curUserId) return;
                
                domLoading.current = setTimeout(async()=>{
                    createPeerConnection(user_id).then(pc=>{
                        
                        // 添加本地音频轨道
                        localStream.current?.getTracks().forEach(track => {
                            pc.addTrack(track, localStream.current!);
                        });
                        
                        
                        // 创建并发送offer
                        pc.createOffer({
                            offerToReceiveAudio: true,
                        }).then(offer => {
                            return pc.setLocalDescription(offer);
                        }).then(() => {
                            if (pc.localDescription) { 
                                socketService.sendOffer(actChannelId, pc.localDescription, user_id);
                            }
                        });
                    })

                },100)

            });
            socketService.joinVoiceChat(actChannelId).then(()=>{
                // 获取当前房间用户并过滤掉自己
                // if(audioRefs.current[curUserId]){
                //     if(localStream.current){
                //         console.log(audioRefs.current[curUserId],11111111111);
                //         audioRefs.current[curUserId].srcObject = localStream.current
                //         setupAudioLevelMonitor(localStream.current,curUserId)
                //     }
                // }
                const otherUsers = chatRoomUsers.filter(user => user.user_id !== curUserId);
                otherUsers.forEach(async (user) => {
                    const pc = await createPeerConnection(user.user_id);
                    
                    // 添加本地音频轨道
                    localStream.current?.getTracks().forEach(track => {
                        pc.addTrack(track, localStream.current!);
                    });
                    
                    // 创建并发送offer
                    const offer = await pc.createOffer({
                        offerToReceiveAudio: true,
                    });
                    await pc.setLocalDescription(offer);
                    if(pc.localDescription){
                        socketService.sendOffer(actChannelId, pc.localDescription, user.user_id);
                    }else{
                        console.error("无法获取本地描述");
                    }
                });
            })
            messageApi.info('请佩戴耳机，以降低回音')
        }
    }

    // // 添加新音频流到混音器
    // const addStreamToMixer = (stream: MediaStream, id: string) => {
    //     if (!isRecording || !audioContextRef.current || !destinationRef.current) return;
        
    //     try {
    //         const source = audioContextRef.current.createMediaStreamSource(stream);
    //         source.connect(destinationRef.current);
    //         audioSourcesRef.current[id] = source;
    //         console.log(`Added audio source for ${id}`);
    //     } catch (error) {
    //         console.error("Error adding stream to mixer:", error);
    //     }
    // };

    // // 移除音频流
    // const removeStreamFromMixer = (id: string) => {
    //     const source = audioSourcesRef.current[id];
    //     if (source) {
    //         source.disconnect();
    //         delete audioSourcesRef.current[id];
    //         console.log(`Removed audio source for ${id}`);
    //     }
    // };

    // // 开始录音
    // const startRecording = async () => {
    //     if (!audioContextRef.current) {
    //         audioContextRef.current = new AudioContext();
    //     }
        
    //     // 创建目标节点
    //     const destination = audioContextRef.current.createMediaStreamDestination();
    //     const mixedStream = destination.stream;
        
    //     // 添加所有音频源（当前用户+其他用户）
    //     if (localStream.current) {
    //         const source = audioContextRef.current.createMediaStreamSource(localStream.current);
    //         source.connect(destination);
    //         audioSourcesRef.current.push(source);
    //     }
        
    //     Object.values(audioRefs.current).forEach(audio => {
    //         if (audio && audio.srcObject) {
    //             const source = audioContextRef.current!.createMediaStreamSource(audio.srcObject as MediaStream);
    //             source.connect(destination);
    //             audioSourcesRef.current.push(source);
    //         }
    //     });
        
        
    //     // 创建MediaRecorder
    //     mediaRecorderRef.current = new MediaRecorder(mixedStream);
    //     recordedChunksRef.current = [];
        
    //     mediaRecorderRef.current.ondataavailable = (event) => {
    //         if (event.data.size > 0) {
    //             recordedChunksRef.current.push(event.data);
    //         }
    //     };
        
    //     mediaRecorderRef.current.onstop = () => {
    //         const blob = new Blob(recordedChunksRef.current, { type: 'audio/mp3' });
    //         console.log(blob);
            
    //         const url = URL.createObjectURL(blob);
            
    //         // 创建下载链接
    //         const a = document.createElement('a');
    //         a.style.display = 'none';
    //         a.href = url;
    //         a.download = `voice-recording-${new Date().toISOString().slice(0, 19)}.mp3`;
    //         document.body.appendChild(a);
    //         a.click();
            
    //         // 清理
    //         window.setTimeout(() => {
    //             document.body.removeChild(a);
    //             URL.revokeObjectURL(url);
    //         }, 100);
    //     };
        
    //     mediaRecorderRef.current.start();
    //     setIsRecording(true);
        
    //     // 10分钟自动停止
    //     recordingIntervalRef.current = setTimeout(() => {
    //         stopRecording();
    //     }, 10 * 60 * 1000);
    // };

    // // 停止录音
    // const stopRecording = () => {
    //     if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') {
    //         mediaRecorderRef.current.stop();
    //     }
        
    //     if (recordingIntervalRef.current) {
    //         clearTimeout(recordingIntervalRef.current);
    //         recordingIntervalRef.current = null;
    //     }
        
    //     // 断开所有音频源
    //     audioSourcesRef.current.forEach(source => source.disconnect());
    //     audioSourcesRef.current = [];
        
    //     setIsRecording(false);
    // };

    useEffect(()=>{
        if(isConnect){
            socketService.onSendChatUsers((users)=>{
                setChatRoomUsers(users.users.map(user=>{
                    return {...user}
                }))
            })
            socketService.onUsersChange((data)=>{
                if(data.type==='join'){
                    setChatRoomUsers(prevUsers=>{
                        return [...prevUsers, data.user]
                    })
                    
                    if(data.user.user_id === curUserId){
                        setTimeout(()=>{
                            userCards.current[curUserId].style.opacity = '1'
                            audioRefs.current[curUserId].srcObject = localStream.current
                            audioRefs.current[curUserId].muted = true
                            if(!localStream.current) return
                            setupAudioLevelMonitor(localStream.current,curUserId)
                        },10)
                    }
                }
                if(data.type==='leave'){
                    setChatRoomUsers(prevUsers=>{
                        return prevUsers.filter(user=>user.user_id!==data.user.user_id)
                    })
                    delete audioRefs.current[data.user.user_id]
                    delete userCards.current[data.user.user_id]
                }
            })
            socketService.joinVoiceChannel(actChannelId);
        }
        return ()=>{
            socketService.offSendChatUsers();
            socketService.leaveVoiceChannel(actChannelId);
        }
    },[isConnect])
    
    useEffect(()=>{
        if(!voiceChated){
            if(soundTimmer.current) clearInterval(soundTimmer.current)
        }
        
        return ()=>{
            if(voiceChated){
                // 清理事件监听
                socketService.offOffer();
                socketService.offAnswer();
                socketService.offIceCandidate();
                socketService.offUserLeft()
                socketService.offUserJoined()
                if(localStream.current) {
                    localStream.current.getTracks().forEach(track => track.stop())
                    localStream.current = null;
                }
                // 关闭所有peer连接
                Object.values(peerConnections.current).forEach(pc => pc.close());
                peerConnections.current = {};
            }
        }
    },[voiceChated])

    useEffect(() => {
        // 清理函数：离开频道
        
        return () => {
            localStorage.removeItem(actChannelId+'msg')
            if (actChannelId) {
                socketService.leaveVoiceChat(actChannelId)
            }
        };
    }, []);

    return (
        <>
            {contextHolder}
            <div className="voiceChat_box">
                <div className="voiceChat_header">
                    <div className="voiceChat_title">
                        <span>#</span>
                        <div>{actChannelId}</div>
                    </div>
                </div>
                <div className="voiceChat_content">
                    <div className="voiceChat_content_left">
                        <div className="voiceChat_room_content">
                            {chatRoomUsers.map((item)=>
                                <div key={item.user_id} ref={(e)=>addToCardRefs(e,item.user_id)} className="user_card_wrapper">
                                    <UserCard 
                                        avatarUrl={item.avatar_url} 
                                        name={item.username}
                                        volume={userVolumes[item.user_id] || 0}
                                        isCurrentUser={item.user_id === curUserId} // 标识是否是当前用户
                                    />
                                    <audio 
                                        autoPlay
                                        playsInline 
                                        id={'audio'+item.user_id} 
                                        ref={(el)=>addToRefs(el, item.user_id)}
                                    ></audio>
                                </div>
                            )}
                        </div>
                        <div className="voiceChat_toobar">
                            <Tooltip title={voiceChated ? '断开连接' : '连接'}>
                                <div 
                                    className={classNames('voiceChat_toobar_action',voiceChated?'disconnect_action':'connect_action')}
                                    onClick={toggleConnect}
                                >
                                    {voiceChated?
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
                                        <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2"/>
                                        <line x1="20" y1="4" x2="0" y2="22"/>
                                    </svg>
                                    :<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
                                        <path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2"/>
                                        {/* <path d="M15 7a2 2 0 0 1 2 2"/>
                                        <path d="M15 3a6 6 0 0 1 6 6"/> */}
                                    </svg>
                                    }
                                </div>
                            </Tooltip>
                            {/* <Tooltip title={isRecording ? '停止录音' : '开始录音'}>
                                <div 
                                    className={classNames('voiceChat_toobar_action', isRecording ? 'recording_action' : '')}
                                    onClick={() => isRecording ? stopRecording() : startRecording()}
                                >
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                        {isRecording ? (
                                            <rect x="9" y="3" width="6" height="18" rx="2" fill="currentColor"/>
                                        ) : (
                                            <path fill="currentColor" d="M12,15A4,4 0 0,0 16,11V5A4,4 0 0,0 12,1A4,4 0 0,0 8,5V11A4,4 0 0,0 12,15M19,11C19,14.53 16.39,17.44 13,17.93V21H11V17.93C7.61,17.44 5,14.53 5,11H7A5,5 0 0,0 12,16A5,5 0 0,0 17,11H19Z"/>
                                        )}
                                    </svg>
                                </div>
                            </Tooltip> */}
                            <div></div>
                        </div>
                    </div>
                    <div className="voiceChat_content_right">
                        <TextChat 
                            actChannelId={actChannelId} 
                            key={actChannelId}
                            inputActions={['emotion']}
                            ref={textChatRef}
                        ></TextChat>
                    </div>
                </div>
            </div>
        </>
        
    )
})


export default VoiceChat